package com.shop.cereshop.app.controller.shop;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shop.cereshop.app.page.shop.PlatformShop;
import com.shop.cereshop.app.param.shop.ShopParam;
import com.shop.cereshop.app.service.business.CereBusinessBuyerUserService;
import com.shop.cereshop.app.service.buyer.CereBuyerUserService;
import com.shop.cereshop.app.service.role.CereBusinessRoleService;
import com.shop.cereshop.app.service.role.CerePlatformRoleService;
import com.shop.cereshop.app.service.shop.CerePlatformShopservice;
import com.shop.cereshop.app.service.shop.CereShopConversionService;
import com.shop.cereshop.app.service.shop.CereShopVisitService;
import com.shop.cereshop.app.service.shop.CereUserShopVisitService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.ParamEnum;
import com.shop.cereshop.commons.domain.business.CereBusinessBuyerUser;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.role.CereBusinessRole;
import com.shop.cereshop.commons.domain.role.CerePlatformRole;
import com.shop.cereshop.commons.domain.shop.CerePlatformShop;
import com.shop.cereshop.commons.domain.shop.CereShopConversion;
import com.shop.cereshop.commons.domain.shop.CereShopVisit;
import com.shop.cereshop.commons.domain.shop.CereUserShopVisit;
import com.shop.cereshop.commons.domain.shop.bo.CereUserShopVisitBo;
import com.shop.cereshop.commons.domain.shop.vo.CereUserShopVisitVo;
import com.shop.cereshop.commons.enums.RoleEnum;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/userShop/visit")
/**
 * 注解方式生成日志对象，指定topic生成对象类名
 */
@Slf4j(topic = "CereUserShopVisitController")
@Api(value = "用户访问店铺记录模块", tags = "用户访问店铺记录模块")
public class CereUserShopVisitController {


    @Autowired
    private CereUserShopVisitService cereUserShopVisitService;

    @Autowired
    private CereBuyerUserService cereBuyerUserService;

    @Autowired
    private CerePlatformShopservice cerePlatformShopservice;

    @Autowired
    private CereShopVisitService cereShopVisitService;

    @Autowired
    private CereBusinessBuyerUserService cereBusinessBuyerUserService;

    @Autowired
    private CereBusinessRoleService cereBusinessRoleService;

    @Autowired
    private CereShopConversionService cereShopConversionService;




    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "添加或更新用户访问店铺记录")
    public Result<PlatformShop> saveOrUpdate(@RequestBody CereUserShopVisit cereUserShopVisit, HttpServletRequest request) throws CoBusinessException {
        String token = request.getHeader("Authorization");
        CereBuyerUser user=null;
        if(!EmptyUtils.isEmpty(token)){
            //根据token查询用户信息
            user=cereBuyerUserService.findByToken(token);
        }
        Integer[] shopPageViewArr = {5,9,14};
        Random random = new Random();
        cereUserShopVisit.setBuyerUserId(user.getBuyerUserId());
        //添加店铺与商家关联关系
        CereBusinessBuyerUser cereBusinessBuyerUser = cereBusinessBuyerUserService.queryByShopIdAndByBuyerUserId(cereUserShopVisit.getShopId(), cereUserShopVisit.getBuyerUserId());
        if (cereBusinessBuyerUser == null){
            CereBusinessRole cereBusinessRole = cereBusinessRoleService.queryByDesc(RoleEnum.TOURIST.getCode());
            cereBusinessBuyerUser = new CereBusinessBuyerUser();
            cereBusinessBuyerUser.setShopId(cereUserShopVisit.getShopId());
            cereBusinessBuyerUser.setBuyerUserId(cereUserShopVisit.getBuyerUserId());
            //第一次访问设置为游客
            cereBusinessBuyerUser.setRoleId(cereBusinessRole.getRoleId());
            cereBusinessBuyerUserService.save(cereBusinessBuyerUser);
        }



        CereShopVisit todayRecord = cereShopVisitService.getTodayRecord(cereUserShopVisit.getBuyerUserId(), cereUserShopVisit.getShopId());
        if (todayRecord == null){
            CereShopVisit cereShopVisit = new CereShopVisit();
            BeanUtils.copyProperties(cereUserShopVisit,cereShopVisit);
            Long shopId = cereShopVisit.getShopId();
            if (shopId == null){
                throw new CoBusinessException("未传入shopId");
            }
            PlatformShop shop = cerePlatformShopservice.getById(shopId);
            CerePlatformShop platformShop = new CerePlatformShop();
            platformShop.setShopId(shop.getShopId());
            platformShop.setShopPageView(shop.getShopPageView() + shopPageViewArr[random.nextInt(shopPageViewArr.length)]);
            cerePlatformShopservice.updateById(platformShop);
            String time = TimeUtils.yyMMddHHmmss();
            cereShopVisit.setVisitTime(time);
            cereShopVisitService.save(cereShopVisit);

            //增加店铺转化信息（访问店铺）
            CereShopConversion cereShopConversion=new CereShopConversion();
            cereShopConversion.setShopId(shopId);
            cereShopConversion.setBuyerUserId(user.getBuyerUserId());
            cereShopConversion.setCreateTime(time);
            cereShopConversion.setType(ParamEnum.CONVERSION_VISIT.getCode());
            cereShopConversionService.insert(cereShopConversion);
        }

        CereUserShopVisit cereUserShopVisitOld
                = cereUserShopVisitService.getOne(new LambdaQueryWrapper<CereUserShopVisit>()
                                .eq(CereUserShopVisit::getBuyerUserId,user.getBuyerUserId())
        .eq(CereUserShopVisit::getShopId,cereUserShopVisit.getShopId()));
        if (cereUserShopVisitOld != null){
            cereUserShopVisit.setId(cereUserShopVisitOld.getId());
        }
        cereUserShopVisit.setVisitTime(new Date());
        cereUserShopVisit.setBuyerUserId(user.getBuyerUserId());
        return new Result(cereUserShopVisitService.saveOrUpdate(cereUserShopVisit), CoReturnFormat.SUCCESS);
    }


    @GetMapping("/queryList")
    @ApiOperation(value = "查询当前用户访问记录")
    public Result<List<CereUserShopVisitVo>> queryList(CereUserShopVisitBo bo,HttpServletRequest request) throws CoBusinessException {
        String token = request.getHeader("Authorization");
        CereBuyerUser user=null;
        if(!EmptyUtils.isEmpty(token)){
            //根据token查询用户信息
            user=cereBuyerUserService.findByToken(token);
        }
        bo.setBuyerUserId(user.getBuyerUserId());
        return new Result(cereUserShopVisitService.queryList(bo), CoReturnFormat.SUCCESS);
    }

    @DeleteMapping("/remove/{id}")
    @ApiOperation(value = "移除")
    public Result<Integer> remove(@PathVariable Integer id,HttpServletRequest request) throws CoBusinessException {
        return new Result(cereUserShopVisitService.removeById(id), CoReturnFormat.SUCCESS);
    }

    public static void main(String[] args) {

    }
}
